import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mokeng/widgets/widgets.dart';

TabBar buildTabBar(List<String> tabTitles, TabController controller) {
  return TabBar(
    padding: EdgeInsets.all(4.w),
    controller: controller,
    indicatorWeight: 12.h,
    isScrollable: true,
    tabAlignment: TabAlignment.start,
    dividerHeight: 0,
    labelPadding: EdgeInsets.symmetric(horizontal: 10.w),
    indicatorPadding: EdgeInsets.symmetric(vertical: 6.h),
    indicator: MyUnderlineTabIndicator(
      wantWidth: 16.w,
      borderSide: BorderSide(width: 4.w, color: Colors.red),
    ),
    tabs: buildTabBarTabs(tabTitles, controller),
  );
}

List<Widget> buildTabBarTabs(List<String> tabTitles, TabController controller) {
  return tabTitles
      .asMap()
      .entries
      .map((entry) => AnimatedBuilder(
            animation: controller.animation!,
            builder: (ctx, snapshot) {
              final forward = controller.offset > 0;
              final backward = controller.offset < 0;
              int fromIndex;
              int toIndex;
              double progress;
              // Tab
              if (controller.indexIsChanging) {
                fromIndex = controller.previousIndex;
                toIndex = controller.index;
                progress = (controller.animation!.value - fromIndex).abs() /
                    (toIndex - fromIndex).abs();
              } else {
                // Scroll
                fromIndex = controller.index;
                toIndex = forward
                    ? fromIndex + 1
                    : backward
                        ? fromIndex - 1
                        : fromIndex;
                progress = (controller.animation!.value - fromIndex).abs();
              }
              var flag = entry.key == fromIndex
                  ? 1 - progress
                  : entry.key == toIndex
                      ? progress
                      : 0.0;
              return Container(
                padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 1),
                child: AnimatedScale(
                  scale: 1 + double.parse((flag * 0.2).toStringAsFixed(2)),
                  duration: const Duration(milliseconds: 100),
                  child: Text(
                    entry.value,
                    style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                        color: Colors.black),
                  ),
                ),
              );
            },
          ))
      .toList();
}
